package org.jradweb.core.orm;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

import org.apache.log4j.Logger;
import org.hibernate.EntityMode;
import org.hibernate.SessionFactory;
import org.hibernate.metadata.ClassMetadata;
import org.springframework.context.ApplicationContext;

public class HibernateUtils {
	private static final Logger log=Logger.getLogger(HibernateUtils.class);
	
	public static Map<Class, GenericDao> getModelAndDaoList(
			ApplicationContext ctx) {
		Map<Class, GenericDao> result = new HashMap<Class, GenericDao>();

		Map map = ctx.getBeansOfType(SessionFactory.class);
		SessionFactory sf = null;
		for (Object key : map.keySet()) {
			Object bean = map.get(key);
			if (SessionFactory.class.isInstance(bean)) {
				sf = (SessionFactory) bean;
				break;
			}
		}
		Collection<ClassMetadata> classMetaDatas = sf.getAllClassMetadata()
				.values();
		for (ClassMetadata cmd : classMetaDatas) {

			Class persistentClass = cmd.getMappedClass(EntityMode.POJO);
			result.put(persistentClass, getDao(persistentClass, ctx));

		}

		return result;
	}

	private static GenericDao getDao(Class clazz, ApplicationContext appCtx) {
		String name = clazz.getName();
		name = name.substring(name.lastIndexOf('.'));

		String[] beans = appCtx.getBeanDefinitionNames();
		for (String key : beans) {
			Object bean = appCtx.getBean(key);
			if (GenericDao.class.isInstance(bean)) {
				String dao="dao" + name + "Dao";
				 
				if (key.indexOf(dao) > 0){
					log.info("Founded model \""+clazz+"\" and dao bean \""+key+"\".");
					return (GenericDao) bean;
				}
			}
		}
		return null;
	}

}
